package listbyorder.access001_100.test41;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/31 15:48
 */
public class Solution2 {

    // 方法二： 直接使用原生的数组
    public int firstMissingPositive(int[] nums) {
        if (nums == null || nums.length == 0) return -1;
        int len = nums.length;
        boolean flag = true;
        while (flag) {
            flag = false;
            for (int i = 0; i < nums.length; i++) {
                if (i != nums[i] - 1 && nums[i] > 0 && nums[i] <= len && nums[nums[i] - 1] != nums[i]) {
                    swap(nums, i, nums[i] - 1);
                    flag = true;
                }
            }
        }
        for (int i = 0; i < len; i++) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        return len + 1;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
